
package projectx.transaction;

import java.sql.Connection;
import java.sql.SQLException;

import projectx.core.base.ProjectXSystemException;
import projectx.core.base.ProjectXUserException;
import projectx.core.base.ThreadContext;
import projectx.db.DbUtil;
import projectx.db.ProjectXSQLException;


public abstract class DbTransaction extends Transaction{

    //--------------------------------------------------------------------------
    //   S T A T I C   M E M B E R S
    //
    //--------------------------------------------------------------------------
    private static final long   INTERVAL_MSEC = 30 * 1000; // 30 sec


    //--------------------------------------------------------------------------
    //   M E M B E R S
    //
    //--------------------------------------------------------------------------
    private Connection _conn;


    //--------------------------------------------------------------------------
    //   C O N S T R U C T O R S
    //
    //--------------------------------------------------------------------------
 
    protected DbTransaction(){

        super( null, INTERVAL_MSEC );
    }

    protected DbTransaction( String funcId ){

        super( DbUtil.chopId( funcId ), INTERVAL_MSEC );
        ThreadContext.setCurrentAuth(_funcId);

    }


    //--------------------------------------------------------------------------
    //   M E T H O D S
    //
    //--------------------------------------------------------------------------

    public String getTrxType(){
    	return "db";
    }

    public void initialize() throws ProjectXSystemException {

        _log.debug( "DB conn initialize" );
        ThreadContext.setConnection();
        _conn = ThreadContext.getConnection();
        _initialized = true;
    }

    public abstract Object execute() throws ProjectXUserException, ProjectXSystemException;

    public void commit() throws ProjectXSystemException {
        _log.debug( "DB commit" );

        try{
        	if ( _conn == null || _conn.isClosed() ){
        		return;
        	}
        	
        	_conn.commit();
        }catch(SQLException se){
        	throw new ProjectXSQLException( se );
        }
    }
    public void rollback(){
    	_log.debug( "DB rollback" );

    	try{

        	if ( _conn == null || _conn.isClosed() ){
        		return;       	
        	}
        	_conn.rollback();

        }catch(SQLException se){
        	_log.fatal(se);
        }
    }

    public void release(){
    	_log.debug( "DB connection close" );

        _initialized = false;
        
        try{
        	if ( _conn == null || _conn.isClosed() ){
        		return;
        	}

        	_conn.close();
        }catch(SQLException se){
        	se.printStackTrace();
        }
    }

}
